/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package multicast;

import common.MessageModel;
import common.Message_Type;
import common.Translate;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;

/**
 * 通过组播/广播获取教师的开启的端口和地址
 *
 * @author Eugene-Forest
 */
public class GetPortThread extends Thread {

    private Integer destPort = 0;
    private boolean success = false;
    private InetAddress destAddress;

    public synchronized int get_port() {
        try {
            if (success) {
                return destPort;
            } else {
                wait();
            }
        } catch (Exception e) {
        }
        return destPort;
    }

    public synchronized InetAddress get_Address() {
        try {
            if (success) {
                return destAddress;
            } else {
                wait();
            }
        } catch (Exception e) {
        }
        return destAddress;
    }

    @Override
    public void run() {
        synchronized (this) {
            MulticastSocket multicastSocket;
            try {
                multicastSocket = new MulticastSocket(10000);
                InetAddress address = InetAddress.getByName("239.0.0.1");
                multicastSocket.joinGroup(address);
                byte[] buf = new byte[1024];
                DatagramPacket datagramPacket = new DatagramPacket(buf, buf.length);
                while (true) {
                    // 接收数据，同样会进入阻塞状态
                    multicastSocket.receive(datagramPacket);
                    //分割byte[]并获取数据以及数据转换
                    byte[] info = new byte[datagramPacket.getLength()];
                    //将目标字节数组获取
                    System.arraycopy(buf, 0, info, 0, datagramPacket.getLength());
                    MessageModel messageModel = (MessageModel) Translate.byteToObject(info);
                    if (messageModel != null && messageModel.getType() == Message_Type.Calling_Port) {
                        String message = messageModel.getMessageString();
                        destAddress = datagramPacket.getAddress();
                        destPort = Integer.valueOf(message);
                        success = true;
                        notifyAll();
                        break;
                    }
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } // 接收数据时需要指定监听的端口号
            catch (NumberFormatException e) {
                e.printStackTrace();
            }
        }
    }
}
